package com.cloudcc.mobile.adapter;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.IMMessageDB;
import com.cloudcc.mobile.entity.RecentItem;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.photo.Constants;
import com.lidroid.xutils.exception.DbException;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class MessageListAdapter extends BaseAdapter {
	private List<RecentItem> list;
	private Context context;
	private IMMessageDB db;

	public MessageListAdapter(List<RecentItem> list, Context context) {
		super();
		this.list = list;
		this.context = context;
		db = new IMMessageDB(context, UserManager.getManager().getUser().userId
				+ "IM");
	}

	// 更新数据
	public void changeData(List<RecentItem> list) {
		this.list = list;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public RecentItem getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.messagelist_item, null);
			holder = new ViewHolder();
			holder.name = (TextView) convertView
					.findViewById(R.id.message_name);
			holder.context = (TextView) convertView
					.findViewById(R.id.message_text);
			holder.num = (TextView) convertView
					.findViewById(R.id.message_number);
			holder.time = (TextView) convertView
					.findViewById(R.id.message_time);
			holder.icon = (ImageView) convertView
					.findViewById(R.id.message_list_icon);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		RecentItem recent = getItem(position);
		holder.name.setText(recent.getName());
		String message = recent.getMessage();
		if (Tools.isNull(message)) {
			holder.context.setText("...");
		} else {
			if (message.length() > 10) {
				String a = message.substring(0, 9);
				holder.context.setText(a + "...");
			} else {
				holder.context.setText(message + "...");
			}
		}
		holder.time.setText(Tools.getTime(recent.getTime()));
		long num = 0;
		try {
			num = db.getNewIMMessageNum(recent.getFromUserId());
		} catch (DbException e) {
			e.printStackTrace();
		}
		if (num < 1) {
			holder.num.setVisibility(View.GONE);
		} else {
			holder.num.setVisibility(View.VISIBLE);
			holder.num.setText("" + num);
		}
		String iconid = recent.getFromUserId();
		String icon = iconid + ".png";
		String path = Tools.getImagePath("/CloudCC/UserIcon/");
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		String iconpath = Tools.getImagePath("/CloudCC/UserIcon/") + "/" + icon;
		File file = new File(iconpath);
		if (file.exists()) {
			ImageLoader.getInstance().displayImage("file://" + iconpath,
					holder.icon, Constants.chater_index_icon_optionst);
		} else {
			ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(
					icon, "/CloudCC/UserIcon/");
			String url = UrlTools.url + UrlTools.url_path
					+ "serviceName=showChatterImage&type=user&id=" + iconid
					+ "&binding=" + AppContext.binding;
			ImageLoader.getInstance().displayImage(url, holder.icon,
					Constants.chater_index_icon_optionst, animateFirstListener);
		}

		return convertView;
	}

	class ViewHolder {
		private TextView name;
		private TextView time;
		private TextView context;
		private TextView num;
		private ImageView icon;
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {
		private String id;
		private String path;

		public AnimateFirstDisplayListener(String imageId, String path) {
			this.id = imageId;
			this.path = path;
		}

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
					ImageUtils.saveImage(path, id, loadedImage);
				}
			}
		}
	}
}
